package com.ytjj.qmyx.admin.controller.data;

import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.constants.RedisConstants;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.admin.model.request.dataStatistics.DataStatisticsRequest;
import com.ytjj.qmyx.admin.model.response.DataStatisticsResponse;
import com.ytjj.qmyx.admin.service.data.DataService;
import com.ytjj.qmyx.admin.service.data.DataStatisticService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;

/**
 * 数据分析统计
 *
 *
 * @version 1.0
 * 
 */

@RestController
@RequestMapping("/dataStatistics")
public class DataStatisticController {

    @Resource
    private DataStatisticService dataStatisticService;
    @Resource
    private DataService dataService;
    @Resource
    private RedisService redisService;

    /**
     * 获取所有渠道数据--实时查询
     */
    @PostMapping("/getAllChannelData")
    public CommonResult getAllChannelData(@RequestBody DataStatisticsRequest dataStatisticsRequest) {
        String recordKey = RedisConstants.CHANNEL_STATISTIC + dataStatisticsRequest.getPlatform()+"-"+dataStatisticsRequest.getChannel()+"-"+dataStatisticsRequest.getSearchDate();
        String respStr = redisService.get(recordKey);
        DataStatisticsResponse dataStatisticsResponse=null;
        if (StringUtils.isNotEmpty(respStr)) {
            dataStatisticsResponse=JSONObject.parseObject(respStr, DataStatisticsResponse.class);
        }else {
            dataStatisticsResponse = dataStatisticService.getAllChannelData(dataStatisticsRequest);
            redisService.set(recordKey, JSONObject.toJSONString(dataStatisticsResponse));
            redisService.expire(recordKey, 60);
        }
        return CommonResult.success(dataStatisticsResponse);
    }

    @GetMapping("timing")
    public CommonResult timingData(@RequestParam(required = false) LocalDate localDate) {
        new Thread(() -> {
            dataService.timing(localDate);
        }).start();
        return CommonResult.success();
    }

    @GetMapping("getChannel")
    public CommonResult getChannel(@RequestParam String searchDate, @RequestParam String platform) {
        return CommonResult.success(dataService.getChannel(searchDate, platform));
    }
}
